import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { quasar, transformAssetUrls } from '@quasar/vite-plugin'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import postCssPxToRem from "postcss-pxtorem"
import path from 'path'

// https://vitejs.dev/config/
export default ({ mode }: any ) =>  {

  const env = loadEnv(mode, process.cwd());

  return defineConfig({
    plugins: [
      VueSetupExtend(),
      vue({
      template: {transformAssetUrls},
        script:{
          defineModel:true
        }
    }),
      quasar({
        sassVariables: 'src/quasar-variables.sass'
      }),
    ],
    define: {'process.env': {}},
    resolve: {
      alias: {
        // 如果报错__dirname找不到，需要安装node,执行npm install @types/node --save-dev
        "@": path.resolve(__dirname, "src"),
        "views": '@/views',
        "assets": '@/assets',
        "common": '@/common',
        "components": '@/Library',
        "store": '@/store',
        "router": '@/router',
        "hook": '@/hook',
      },
      // 省略文件后缀
      extensions: ['', '.js', '.json', '.vue', '.scss', '.css', '.ts']
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
          additionalData: `@import "${path.resolve(__dirname, 'src/assets/styles/variables.less')}";`,
          additionalData2: `@import "${path.resolve(__dirname, 'src/assets/styles/mixins.less')}";`
        },
      },
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 16, // 1rem的大小
            propList: ['*'], // 需要转换的属性，这里选择全部都进行转换
          })
        ]
      },
    },
    base: env.VITE_PUBLIC_PATH,
    server: {
      host: "0.0.0.0",
      port: 8888,
    },
    build: {
      outDir: "dist",
      // 9月更新
      assetsDir: "assets", //指定静态资源存放路径
      sourcemap: true, //是否构建source map 文件
      // 10月更新
      minify: "terser", // 混淆器，terser 构建后文件体积更小，'terser' | 'esbuild'
      chunkSizeWarningLimit: 1500, //chunk 大小警告的限制，默认500KB
      rollupOptions: {
        output: {
          // 最小化拆分包
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
          chunkFileNames: 'static/js/[name]-[hash].js', // 用于命名代码拆分时创建的共享块的输出命名，[name]表示文件名,[hash]表示该文件内容hash值
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
        }
      },
      terserOptions: {
        // 生产环境移除console
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
        // 10月更新
        output: {
          comments: true, // 去掉注释内容
        },
      },
    },
    publicDir: 'public',
  })
}
